from docx import Document
from docx.shared import Cm,Pt
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
from compose_test import combine_docx_line, combine_docx_page
from PIL import Image

def create_temp(docx, name):
    result_path_list = []
    for i in range(len(name)):
        result_path = r'./'+ name[i] +'.docx'
        docx.save(result_path)
        result_path_list.append(result_path)
    return result_path_list

def make_temp_docx(result_path_list, name, Class, pic_path, image_folder):
    for i in range(len(result_path_list)):
        docx = Document(result_path_list[i])
        tables = docx.tables
        table = tables[0]
        # Add name
        run_name = table.cell(3,8).paragraphs[0].add_run(name[i])
        run_name.font.name = '楷体'
        run_name.font.size = Pt(14)
        rn = run_name._element
        rn.rPr.rFonts.set(qn('w:eastAsia'), '楷体')
        table.cell(3,8).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        

        # Add class
        run_class = table.cell(5,8).paragraphs[0].add_run(Class[i])
        run_class.font.name = '楷体'
        run_class.font.size = Pt(14)
        rc = run_class._element
        rc.rPr.rFonts.set(qn('w:eastAsia'), '楷体')
        table.cell(5,8).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.DISTRIBUTE
        run_class = ''

        # Add Picture
        f = Image.open((str(image_folder +'/'+ str(pic_path[i]))))
        f.save((str(image_folder +'/'+ str(pic_path[i]))))
        f.close
        run_pic = table.cell(3,15).paragraphs[0].add_run()
        pic = run_pic.add_picture(str(image_folder + '/' + str(pic_path[i])))
        pic.height = Cm(3.29)
        pic.width = Cm(2.44)
        pic = ''
        docx.save(result_path_list[i])

def combine_results(result_path_list, target):
    first_file = result_path_list[0]
    result_path_list.pop(0)
    count = 0
    for i in result_path_list:
        if count == 2:
            combine_docx_page(first_file, i)
            count = 0
        else:
            combine_docx_line(first_file, i)
            count += 1
    old_docx = Document(first_file)
    old_docx.save(target)
    result_path_list.append(first_file)
    for i in result_path_list:
        os.remove(i)


print("导入合成模块成功！")